package org.jackysoft.config;

import javax.annotation.Resource;
import javax.jms.ConnectionFactory;
import javax.servlet.ServletContext;

import org.apache.activemq.command.ActiveMQQueue;
import org.apache.activemq.command.ActiveMQTopic;
import org.apache.activemq.spring.ActiveMQConnectionFactory;
import org.jackysoft.jms.MessageReceiver;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jms.connection.SingleConnectionFactory;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.listener.DefaultMessageListenerContainer;
import org.springframework.web.context.ServletContextAware;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

@Configuration
public class ActivemqConfiguration implements ServletContextAware {

	private ServletContext servletContext;
	private WebApplicationContext wc;   
	private @Value("${brokerURL}") String brokerURL;   
    private MessageReceiver messageReceiver;
	
	@Override
	public void setServletContext(ServletContext servletContext) {
		this.servletContext = servletContext;
		wc = WebApplicationContextUtils.getWebApplicationContext(this.servletContext);

	}
		
	
	public @Bean(name="jmsConnectionFactory") ConnectionFactory jmsConnectionFactory(){
		
		SingleConnectionFactory cs = new SingleConnectionFactory();
	    cs.setTargetConnectionFactory(targetConnectionFactory());
		return cs;
	}
	
	public @Bean ActiveMQConnectionFactory targetConnectionFactory(){
		ActiveMQConnectionFactory amq = new ActiveMQConnectionFactory();
		amq.setBrokerURL(brokerURL);
		return amq;
	}
		
	
	public @Bean JmsTemplate jmsTemplate(){
		JmsTemplate jtemp = new JmsTemplate();
		jtemp.setConnectionFactory(jmsConnectionFactory());		
		return jtemp;
	}
	
	public @Bean(name="queueDestination") ActiveMQQueue queueDestination(){
		ActiveMQQueue queue = new ActiveMQQueue("queue");
		return queue;
	}
	
	public @Bean ActiveMQTopic topicDestination(){
		ActiveMQTopic at = new ActiveMQTopic("topic");
		return at;
	}
	
	
	
	public @Bean DefaultMessageListenerContainer messageListenerContainer(){
		DefaultMessageListenerContainer dl = new DefaultMessageListenerContainer();
		dl.setConnectionFactory(jmsConnectionFactory());
		dl.setDestination(queueDestination());
		dl.setMessageListener(messageReceiver);
		return dl;
		
	}


	@Resource
	public void setMessageReceiver(MessageReceiver messageReceiver) {
		this.messageReceiver = messageReceiver;
	}
	
}
